//
//  PxRegViewController.m
//  OilCard
//
//  Created by Xu Yefeng on 14-5-18.
//  Copyright (c) 2014年 Free. All rights reserved.
//

#import "PxRegViewController.h"
#import "LL360CountDownButton.h"
#import "PxFormValidate.h"

@interface PxRegViewController ()

@end

@implementation PxRegViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
//    [self setLeftBack];
    // Do any additional setup after loading the view.
    [self setLogoTitleViewWithTitle:@"注册"];
    
    self.contentView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    self.contentView.top = [PxGlobal getBaseHeight:NO];
//    CGFloat height = CGRectGetHeight(self.view.frame);// - [PxGlobal getBaseHeight:NO];
//    self.contentView.height = height;
    [self.view addSubview:self.contentView];
    
    self.mobileNo = [PxTextField new];
    self.mobileNo.clearButtonMode = UITextFieldViewModeWhileEditing;
    //    self.mobileNo.text = @"13588116446";
    self.mobileNo.backgroundColor = [UIColor colorWithHTMLStr:@"ffffff"];
    self.mobileNo.keyboardType = UIKeyboardTypeNumberPad;
    self.mobileNo.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入手机号"
                                                                  attributes:@{
                                                                               NSForegroundColorAttributeName: [UIColor colorWithHTMLStr:@"c6c6c6"],
                                                                               NSFontAttributeName : [UIFont systemFontOfSize:15]
                                                                               }];
    
    self.mobileNo.delegate = self;
    [self.contentView addSubview:self.mobileNo];
    
    LLSmallCountDownButton *countdownBtn = [LLSmallCountDownButton countDownButtonWithTimerKey:@"register"];
    [countdownBtn stop];
    [self.contentView addSubview:countdownBtn];
    countdownBtn.backgroundColor = [UIColor colorWithHTMLStr:@"2c75c7"];
    [countdownBtn setSelector:@selector(sendVerify) withTarget:self];
    
    self.verifyCode = [PxTextField new];
    self.verifyCode.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.verifyCode.keyboardType = UIKeyboardTypeNumberPad;
//    self.certificateNo.text = @"330326198812161111";
    self.verifyCode.backgroundColor = [UIColor colorWithHTMLStr:@"ffffff"];
    self.verifyCode.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入验证码"
                                                                          attributes:@{
                                                                                       NSForegroundColorAttributeName: [UIColor colorWithHTMLStr:@"c6c6c6"],
                                                                                       NSFontAttributeName : [UIFont systemFontOfSize:15]
                                                                                       }];
    self.verifyCode.delegate = self;
    [self.verifyCode linkPreField:self.mobileNo];
    [self.contentView addSubview:self.verifyCode];
    
    self.password = [PxTextField new];
    self.password.clearButtonMode = UITextFieldViewModeWhileEditing;
//    self.password.text = @"123456";
    self.password.top = self.verifyCode.bottom;
    self.password.backgroundColor = [UIColor colorWithHTMLStr:@"ffffff"];
    self.password.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入密码"
                                                                               attributes:@{
                                                                                            NSForegroundColorAttributeName: [UIColor colorWithHTMLStr:@"c6c6c6"],
                                                                                            NSFontAttributeName : [UIFont systemFontOfSize:15]
                                                                                            }];
    self.password.delegate = self;
    self.password.secureTextEntry = YES;
    [self.password linkPreField:self.verifyCode];
    [self.contentView addSubview:self.password];
    
    self.passwordCfm = [PxTextField new];
    self.passwordCfm.clearButtonMode = UITextFieldViewModeWhileEditing;
//    self.passwordCfm.text = @"123456";
    self.passwordCfm.top = self.password.bottom;
    self.passwordCfm.backgroundColor = [UIColor colorWithHTMLStr:@"ffffff"];
    self.passwordCfm.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请确认密码"
                                                                          attributes:@{
                                                                                       NSForegroundColorAttributeName: [UIColor colorWithHTMLStr:@"c6c6c6"],
                                                                                       NSFontAttributeName : [UIFont systemFontOfSize:15]
                                                                                       }];
    self.passwordCfm.delegate = self;
    self.passwordCfm.secureTextEntry = YES;
    [self.passwordCfm linkPreField:self.password];
    [self.contentView addSubview:self.passwordCfm];
    
    UIButton *btn = [PxWidgetCreater customerButton];
    [btn setTitle:@"立即注册"];
    [btn setSelector:@selector(gotoRegister) withTarget:self];
    btn.layer.masksToBounds = YES;
    btn.layer.cornerRadius = 10;
    [btn setBackgroundColor:[UIColor colorWithHTMLStr:@"ff4e08"]];
    [self.contentView addSubview:btn];
    
    [self.mobileNo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.contentView).with.offset(-85);
        make.top.equalTo(self.contentView);
        make.height.mas_equalTo(@45);
        make.left.equalTo(self.contentView);
    }];
    
    [countdownBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(@85);
        make.top.equalTo(self.mobileNo);
        make.height.equalTo(self.mobileNo);
        make.left.equalTo(self.mobileNo.mas_right);
    }];
    
    [self.verifyCode mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.contentView);
        make.top.equalTo(self.mobileNo.mas_bottom).with.offset(10);
        make.height.equalTo(self.mobileNo);
        make.left.equalTo(self.mobileNo);
    }];
    
    [self.password mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.contentView);
        make.top.equalTo(self.verifyCode.mas_bottom).with.offset(10);
        make.height.equalTo(self.mobileNo);
        make.left.equalTo(self.mobileNo);
    }];
    
    [self.passwordCfm mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.contentView);
        make.top.equalTo(self.password.mas_bottom).with.offset(10);
        make.height.equalTo(self.mobileNo);
        make.left.equalTo(self.mobileNo);
    }];
    
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.right.equalTo(self.contentView.mas_right).with.offset(-10);
        make.width.equalTo(self.contentView).offset(-20);
        make.top.equalTo(self.passwordCfm.mas_bottom).with.offset(20);
        make.height.equalTo(self.mobileNo);
        make.left.offset(10);
    }];

    self.contentView.contentSize = CGSizeMake(self.contentView.width, btn.bottom);
}

-(void)gotoXieYi
{
//    [self pushViewController:@"PxWebViewController" withIncomingParam:@{@"name":@"用户协议",
//                                                                        @"url":[NSString stringWithFormat:@"%@/static/word/userRegisterProtocol.htm", WEB_HOME]
//                                                                        }];
}

-(void)checkboxClick:(UIButton *)btn
{
    btn.selected = !btn.selected;
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.contentView setContentOffset:CGPointMake(0, 0) animated:YES];
    [self.mobileNo becomeFirstResponder];
}

- (BOOL)isEmpty
{
    NSArray *textFields = self.contentView.subviews;
    for (UIView *view in textFields) {
        if (![view isKindOfClass:[LLYTTextField class]])
            continue;
        LLYTTextField *textField = (LLYTTextField *)view;
        if (nil == textField.text || 0 == textField.text.length) {
            NSString *msg = [NSString stringWithFormat:@"%@ 不能为空", @"  "];//[textField getAbovePlaceHolder]
            
            [self showMSG:msg withType:0];
            
            return YES;
        }
    }
    return NO;
}

- (BOOL)passwordCheck
{
    NSString *password = [self.password.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    NSString *passwordCfm = [self.passwordCfm.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    if ([password isEqualToString:passwordCfm]) {
        return YES;
    }
    
    [self showMSG:@"两次输入的密码不匹配" withType:0];
    
    return NO;
}

- (void)gotoRegister
{
    if (![self isEmpty]) {
        if ([self passwordCheck]) {
            if (![[PxFormValidate sharedInstance] checkPhone:self.mobileNo.text])
                [self showMSG:@"请输入正确手机号" withType:0];
            else {
                if (!self.checkBox.selected)
                    [self showMSG:@"请确认用户协议" withType:0];
                else
                    [self registerUser];
            }
        }
    }
}

- (void)registerUser
{
    NSString *password = [self.password.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    NSString *mobile = [self.mobileNo.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    NSString *verifyCode = [self.verifyCode.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    PxBaseOilNetCmd *cmd = [PxBaseOilNetCmd cmd];
    
    cmd.functionName = TRANS_USER_REGISTER;
    [cmd.paramDic addEntriesFromDictionary:@{@"loginName":mobile,
                                             @"phone":mobile,
                                             @"password":password,
                                             @"verifyCode":verifyCode}];
    
    cmd.businessSuccessHandler = ^(NSDictionary* dic)
    {
        PxUserInfoBean *bean = [[PxUserInfoBean alloc] init];
        bean.loginName = mobile;
        bean.phone = mobile;
        [PxNetSession sharedSession].currentUser = bean;
        [LLAlertService alertWithTip:@"注册成功"];
//        [self.navigationController popToRootViewControllerAnimated:YES];
        [self.navigationController setNavigationBarHidden:NO];
        [self.navigationController popToRootViewControllerAnimated:YES];
    };
    
    cmd.businessErrorHandler = ^(NSDictionary* dic)
    {
        [self showMSG:dic[@"RESPONSECONTENT"] withType:1];
    };
    
    cmd.errorHandler = ^(NSError* error)
    {
        
    };
    
    [LLRestEngine sendCommandRequest:cmd];
}

- (void)showMSG:(NSString *)msg withType:(int)type
{
    NSString *title = @"提示";
    switch (type) {
        case 0:
            title = @"提示";
            break;
        case 1:
            title = @"错误";
            break;
        default:
            break;
    }
//    [[[UIAlertView alloc]initWithTitle:title message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
    [LLAlertService sysAlertWithTip:msg withTitle:title];
}

- (void)sendVerify{
    LLSmallCountDownButton *countdownBtn = [LLSmallCountDownButton countDownButtonWithTimerKey:@"register"];
    
    if (nil == self.mobileNo.text || 0 == self.mobileNo.text.length) {
        [self showMSG:@"请输入手机号" withType:0];

        return;
    }
    
    PxBaseOilNetCmd *cmd = [PxBaseOilNetCmd cmd];
    cmd.functionName = TRANS_USER_SMS_SEND;
    [cmd.paramDic addEntriesFromDictionary:@{@"phone":self.mobileNo.text,
                                             @"loginName":self.mobileNo.text,
                                             @"type":@"p_register"
                                             }];
    
    cmd.businessSuccessHandler = ^(NSDictionary* dic)
    {
        [LLAlertService alertWithTip:@"验证码已发送，请查收"];
        [countdownBtn start];
    };
    
    cmd.businessErrorHandler = ^(NSDictionary* dic)
    {
        [LLAlertService alertWithTip:dic[@"RESPONSECONTENT"]];
    };
    
    cmd.errorHandler = ^(NSError* error)
    {
        
    };
    
    [LLRestEngine sendCommandRequest:cmd];
}

- (void)checkUserAvailable{
    NSString *mobileNo = [self.mobileNo.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    PxBaseOilNetCmd *cmd = [PxBaseOilNetCmd cmd];
    cmd.useSystemHold = NO;
    
    cmd.functionName = TRANS_USER_CHECK;
    [cmd.paramDic addEntriesFromDictionary:@{@"loginName":mobileNo}];
    
    cmd.businessSuccessHandler = ^(NSDictionary* dic)
    {
    };
    
    cmd.businessErrorHandler = ^(NSDictionary* dic)
    {
        [LLAlertService alertWithTip:dic[RESULT_DESC]];
    };
    
    cmd.errorHandler = ^(NSError* error)
    {
        
    };
    
//    [LLRestEngine sendCommandRequest:cmd];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    LLSmallCountDownButton *countDownBtn = [LLSmallCountDownButton countDownButtonWithTimerKey:@"register"];
    [countDownBtn removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
}

@end
